package com.yibai.ssodemo.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.yibai.ssodemo.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/sso")
public class SsoApiController {

    public static String SSO_APP_ID="1002";
    public static String SSO_APP_SERCET="aaa9WfRZykMzYtbAbnYFQtYxHbNIq2kucZAW0ISW5zgrJW67SImVKKHtest";
    public static String SSO_REDIRECT_URI="http://127.0.0.1:8081/callback";
    public static String SSO_URL="https://sso.yibaikeji.net";

    @GetMapping("/login")
    public  void login(HttpServletResponse response) {
        try{
            response.sendRedirect(SSO_URL+"/oauth2/authorize?response_type=code&client_id="+SSO_APP_ID+"&redirect_uri="+SSO_REDIRECT_URI+"&scope=userinfo&state=");
        }catch (Exception e){}
    }

    @GetMapping("/callback")
    public AjaxResult callback(@RequestParam("code") String code) {
        Map<String, Object> ajax = new HashMap<>();
        String token=getSsoToken(code);
        ajax.put("token", token);
        return AjaxResult.success(ajax);
    }


    /**
     * 通过 code 换取 token
     * @param code
     * @return
     */
    private String getSsoToken(String code) {


        String url=SSO_URL+"/oauth2/token?grant_type=authorization_code&code="+code+"&client_id="+SSO_APP_ID+"&client_secret="+SSO_APP_SERCET+"";

        HttpRequest httpRequest= HttpUtil.createGet(url);
        httpRequest.timeout((1000*10));
        httpRequest.header("Content-Type","application/json");
        httpRequest.header("Charset","UTF-8");
        httpRequest.header("Connection","Keep-Alive");
        String res=httpRequest.execute().body();
        log.debug("res:"+res);
        JSONObject jsonObject=new JSONObject(res);

        if(jsonObject.isNull("code")||jsonObject.isNull("data")){
            throw new RuntimeException(jsonObject.getStr("msg"));
        }

        JSONObject data=jsonObject.getJSONObject("data");
        String access_token=data.getStr("access_token");


        /**
         * 调用 查询用户个人信息接口
         */
        url=SSO_URL+"/oauth2/userinfo?access_token="+access_token;
        res=doGet(url);
        jsonObject=new JSONObject(res);
        if(jsonObject.isNull("code")||jsonObject.isNull("data")){
            throw new RuntimeException(jsonObject.getStr("msg"));
        }
        data=jsonObject.getJSONObject("data");

        /**
         *  查询 openid 绑定的用户 （如果存在就直接登录 不存在 就自动创建（或者提示用户 是绑定现有账号 还是 新创建账号 ））
         */
        String openid=data.getStr("openid");

        //登录操作
        StpUtil.login(openid);
        StpUtil.getAnonTokenSession().set("userName",data.getStr("userName"));
        StpUtil.getAnonTokenSession().set("nickName",data.getStr("nickName"));
        StpUtil.getAnonTokenSession().set("phonenumber",data.getStr("phonenumber"));
        StpUtil.getAnonTokenSession().set("avatar",data.getStr("avatar"));


        //获取 登录 token
        String token=StpUtil.getTokenValue();

        return token;
    }


    private String doGet(String url){
        HttpRequest httpRequest=HttpUtil.createGet(url);
        httpRequest.timeout((1000*10));
        httpRequest.header("Charset","UTF-8");
        String res=httpRequest.execute().body();
        return res;
    }



}
